﻿using LiveCharts;
using LiveCharts.Defaults;
using System;
using System.Windows.Forms;
using LiveCharts.Wpf;
using System.Windows.Media;

namespace mccbAvg
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public MysqlBase mysqlBase { get; set; }
        private static string sqlConn = "Database=mccb;Data Source=192.168.1.150;User Id=root;Password=root@3585728;;pooling=false;CharSet=utf8;port=3306;";

        /// <summary>
        /// 窗体加载事件，完成一些初始化工作
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Form1_Load(object sender, EventArgs e)
        {
            try
            {
                //初始化数据库操作类实例
                mysqlBase = new MysqlBase(sqlConn);
                //获取所有可用设备ID
                var dt = mysqlBase.query("select distinct id from average_current;");
                //存在可用设备ID的情况下，将其加载到界面的可用ID列表中
                for (int i = 0; i < dt.Rows.Count; i++)
                    machines.Items.Add(dt.Rows[i][0].ToString().Trim());
                if (machines.Items.Count > 0)
                    machines.SelectedIndex = 0;
                //设置曲线的缩放模式为X轴
                chart.Zoom = ZoomingOptions.X;
                //设置曲线X轴坐标的格式化委托
                chart.AxisX.Add(new Axis
                {
                    LabelFormatter = val => new DateTime((long)val).ToString("MM/dd\nHH:mm")
                });
                //Y轴数据格式化操作委托
                chart.AxisY.Add(new Axis
                {
                    LabelFormatter = val => val.ToString("F2")
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show("窗体初始化异常：" + ex.ToString());
            }
        }

        private void query_Click(object sender, EventArgs e)
        {
            DoQuery();
        }

        private void DoQuery()
        {
            if (machines.SelectedIndex < 0)
            {
                MessageBox.Show("未选中设备");
                return;
            }
            if (string.IsNullOrWhiteSpace(datepicker.Text))
            {
                MessageBox.Show("未选中日期");
                return;
            }
            //清理历史曲线
            chart.Series.Clear();
            //载入新数据
            string selectedDate = datepicker.Value.ToString("yyyy-MM-dd");
            string sql = "select * from average_current where id = " + machines.SelectedItem.ToString() + " and date = '" + selectedDate + "' order by average_current.index asc;";
            var dt = mysqlBase.query(sql);
            if (dt.Rows.Count > 0)
            {
                var ia = new ChartValues<DateTimePoint>();
                var ib = new ChartValues<DateTimePoint>();
                var ic = new ChartValues<DateTimePoint>();
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    //用记录行中的日期和索引号，实例化一个Datetime类型的实例
                    int minutes = int.Parse(dt.Rows[i][2].ToString()) * 10;
                    int hour = minutes / 60;
                    int minute = minutes % 60;
                    DateTime date = DateTime.ParseExact(string.Format(selectedDate + " {0:D2}:{1:D2}:00", hour, minute), "yyyy-MM-dd HH:mm:ss", System.Globalization.CultureInfo.CurrentCulture);
                    //把三相数据记录到对应的集合中去
                    ia.Add(new DateTimePoint(date, float.Parse(dt.Rows[i][3].ToString())));
                    ib.Add(new DateTimePoint(date, float.Parse(dt.Rows[i][4].ToString())));
                    ic.Add(new DateTimePoint(date, float.Parse(dt.Rows[i][5].ToString())));
                }
                //在控件中依次加入三条曲线并设置曲线属性
                AddSeries(new SolidColorBrush(Color.FromRgb(0xfb, 0xc0, 0x2d)), ia, "IA");
                AddSeries(new SolidColorBrush(Color.FromRgb(0x00, 0xc8, 0x53)), ib, "IB");
                AddSeries(new SolidColorBrush(Color.FromRgb(0xff, 0x57, 0x22)), ic, "IC");
                //重置整个绘图区域的缩放级别
                ClearZoom();
            }
        }

        private void AddSeries(SolidColorBrush borderColor, ChartValues<DateTimePoint> points, string name)
        {
            chart.Series.Add(new LineSeries
            {
                Title = name,//名称
                Values = points,//数据点
                StrokeThickness = 2,//线粗
                Stroke = borderColor,//线色
                Fill = Brushes.Transparent,//线条下方的填充色
                LineSmoothness = 1,//平滑度
                PointGeometrySize = 5,//数据点图形大小
                PointForeground = new SolidColorBrush(Color.FromRgb(34, 46, 49))//数据点图形的前景色
            });
        }


        private void ClearZoom()
        {
            if (chart.AxisX.Count > 0 && chart.AxisY.Count > 0)
            {
                chart.AxisX[0].MinValue = double.NaN;
                chart.AxisX[0].MaxValue = double.NaN;
                chart.AxisY[0].MinValue = double.NaN;
                chart.AxisY[0].MaxValue = double.NaN;
            }
        }

        private void reset_Click(object sender, EventArgs e)
        {
            ClearZoom();
        }

        private void machines_SelectedValueChanged(object sender, EventArgs e)
        {
            if (machines.SelectedIndex > -1)
            {
                //清理旧的日期
                availableDate.Items.Clear();
                //获取当前设备所对应的有数据的日期集合并加载到可用日期列表中
                string id = machines.Text.Trim();
                var res = mysqlBase.query("select distinct date from average_current where id = " + id + " order by date asc;");
                if (res.Rows.Count > 0)
                {
                    for (int i = 0; i < res.Rows.Count; i++)
                        availableDate.Items.Add(((DateTime)res.Rows[i][0]).ToString("yyyy-MM-dd"));
                    //加载完毕，选中第一个
                    availableDate.SelectedIndex = 0;
                }
            }
        }

        private void availableDate_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (availableDate.SelectedIndex > -1)
            {
                string dt = availableDate.Text.Trim();
                var date = DateTime.Parse(dt);
                datepicker.Value = date;
                DoQuery();
            }
        }
    }
}
